/**
 * 自定义节点Resize控制器 - SVG圆形拖拽点实现
 * 支持8个方向的拖拽点，使用SVG绘制圆形拖拽点
 */
export class CustomResizeController {
    constructor(cell, container) {
        this.cell = cell
        this.container = container
        this.isResizing = false
        this.currentHandle = null
        this.startPos = { x: 0, y: 0 }
        this.startSize = { width: 0, height: 0 }
        this.startCellPos = { x: 0, y: 0 }

        this.resizeHandles = []
        this.svgContainer = null  // SVG容器
        this.isVisible = false

        this.init()
    }

    init() {
        this.createSVGResizeHandles()
        this.bindEvents()
    }

    /**
     * 创建SVG拖拽点系统
     */
    createSVGResizeHandles() {
        if (this.svgContainer) {
            return
        }
        // 创建SVG容器
        this.svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
        this.svgContainer.setAttribute('class', 'resize-svg-container')

        // 获取节点尺寸用于SVG定位
        const cellSize = this.cell.getSize()

        // 设置SVG容器样式和尺寸
        Object.assign(this.svgContainer.style, {
            position: 'absolute',
            top: '-10px',
            left: '-10px',
            width: `${cellSize.width + 20}px`,
            height: `${cellSize.height + 20}px`,
            pointerEvents: 'none',
            zIndex: '1000',
            //   display: 'none',
            overflow: 'visible'
        })

        // 拖拽点配置（基于SVG坐标系）
        const handleConfigs = [
            //   { type: 'nw', cx: 10, cy: 10, cursor: 'nw-resize' },
            //   { type: 'n', cx: cellSize.width / 2 + 10, cy: 10, cursor: 'n-resize' },
            //   { type: 'ne', cx: cellSize.width - 10, cy: 10, cursor: 'ne-resize' },
            //   { type: 'w', cx: 10, cy: cellSize.height / 2 + 10, cursor: 'w-resize' },
            //   { type: 'e', cx: cellSize.width - 10, cy: cellSize.height / 2 - 10, cursor: 'e-resize' },
            //   { type: 'sw', cx: 10, cy: cellSize.height + 10, cursor: 'sw-resize' },
            //   { type: 's', cx: cellSize.width / 2 - 10, cy: cellSize.height - 10, cursor: 's-resize' },
            { type: 'se', cx: cellSize.width - 10, cy: cellSize.height - 10, cursor: 'se-resize' }
        ]

        // 创建每个圆形拖拽点
        handleConfigs.forEach(config => {
            const circle = this.createSVGCircleHandle(config)
            this.resizeHandles.push(circle)
            this.svgContainer.appendChild(circle)
        })

        // this.container.appendChild(this.svgContainer)
        document.querySelector(`[data-cell-id="${this.cell?.id}"]`)?.appendChild(this.svgContainer)
    }

    /**
     * 创建单个SVG圆形拖拽点
     */
    createSVGCircleHandle(config) {
        const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle')

        // 基础属性
        circle.setAttribute('cx', config.cx)
        circle.setAttribute('cy', config.cy)
        circle.setAttribute('r', '6')
        circle.setAttribute('data-type', config.type)
        // circle.setAttribute('class', `resize-handle resize-handle-${config.type}`)

        // 样式属性
        circle.setAttribute('fill', '#1890ff')
        circle.setAttribute('stroke', '#ffffff')
        circle.setAttribute('stroke-width', '2')
        circle.setAttribute('filter', 'drop-shadow(0 2px 4px rgba(0,0,0,0.3))')

        // 交互样式
        Object.assign(circle.style, {
            cursor: config.cursor,
            pointerEvents: 'all',
            //   transition: 'all 0.2s ease'
        })

        // 悬停效果
        // this.addHoverEffects(circle)

        return circle
    }

    /**
     * 添加悬停效果
     */
    addHoverEffects(circle) {
        circle.addEventListener('mouseenter', () => {
            circle.setAttribute('r', '7')
            circle.setAttribute('fill', '#40a9ff')
            circle.setAttribute('stroke-width', '3')
        })

        circle.addEventListener('mouseleave', () => {
            if (!this.isResizing) {
                circle.setAttribute('r', '6')
                circle.setAttribute('fill', '#1890ff')
                circle.setAttribute('stroke-width', '2')
            }
        })
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 绑定拖拽点事件
        this.resizeHandles.forEach(handle => {
            handle.addEventListener('mousedown', (e) => {
                e.preventDefault()
                e.stopPropagation()
                this.startResize(e, handle)
            })
        })

        // 绑定全局鼠标事件
        this.onMouseMove = this.onMouseMove.bind(this)
        this.onMouseUp = this.onMouseUp.bind(this)
    }

    /**
   * 开始拖拽
   */
    startResize(e, handle) {
        // 阻止事件冒泡和默认行为，避免与画布移动冲突
        e.preventDefault()
        e.stopPropagation()
        e.stopImmediatePropagation()

        this.isResizing = true
        this.currentHandle = handle

        // 记录起始位置
        this.startPos = { x: e.clientX, y: e.clientY }

        // 记录起始尺寸和位置
        this.startSize = this.cell.getSize()
        this.startCellPos = this.cell.getPosition()

        // 添加拖拽样式
        handle.setAttribute('class', handle.getAttribute('class') + ' dragging')

        // 绑定全局事件
        document.addEventListener('mousemove', this.onMouseMove)
        document.addEventListener('mouseup', this.onMouseUp)

        // 禁用文本选择
        document.body.style.userSelect = 'none'
    }

    /**
     * 鼠标移动处理
     */
    onMouseMove(e) {
        // 阻止事件冒泡，避免触发画布的节点移动功能
        e.preventDefault()
        e.stopPropagation()
        e.stopImmediatePropagation()

        if (!this.isResizing || !this.currentHandle) return



        const deltaX = e.clientX - this.startPos.x
        const deltaY = e.clientY - this.startPos.y
        const handleType = this.currentHandle.getAttribute('data-type')
        console.log("🚀 ~onMouseMove  handleType:", handleType)

        const newSize = this.calculateNewSize(handleType, deltaX, deltaY)
        const newPosition = this.calculateNewPosition(handleType, newSize)

        // 更新节点尺寸和位置
        this.cell.setProp('size', newSize)
        if (newPosition) {
            this.cell.setPosition(newPosition)
        }

        // 更新SVG拖拽点位置
        this.updateSVGHandles()
    }

    /**
     * 计算新尺寸
     */
    calculateNewSize(handleType, deltaX, deltaY) {
        let newWidth = this.startSize.width
        let newHeight = this.startSize.height

        switch (handleType) {
            case 'nw':
                newWidth = this.startSize.width - deltaX
                newHeight = this.startSize.height - deltaY
                break
            case 'n':
                newHeight = this.startSize.height - deltaY
                break
            case 'ne':
                newWidth = this.startSize.width + deltaX
                newHeight = this.startSize.height - deltaY
                break
            case 'w':
                newWidth = this.startSize.width - deltaX
                break
            case 'e':
                newWidth = this.startSize.width + deltaX
                break
            case 'sw':
                newWidth = this.startSize.width - deltaX
                newHeight = this.startSize.height + deltaY
                break
            case 's':
                newHeight = this.startSize.height + deltaY
                break
            case 'se':
                newWidth = this.startSize.width + deltaX
                newHeight = this.startSize.height + deltaY
                break
        }

        // 设置最小尺寸限制
        newWidth = Math.max(50, newWidth)
        newHeight = Math.max(30, newHeight)

        return { width: newWidth, height: newHeight }
    }

    /**
     * 计算新位置（左上角拖拽点需要调整位置）
     */
    calculateNewPosition(handleType, newSize) {
        let newX = this.startCellPos.x
        let newY = this.startCellPos.y

        switch (handleType) {
            case 'nw':
                newX = this.startCellPos.x + (this.startSize.width - newSize.width)
                newY = this.startCellPos.y + (this.startSize.height - newSize.height)
                break
            case 'n':
                newY = this.startCellPos.y + (this.startSize.height - newSize.height)
                break
            case 'ne':
                newY = this.startCellPos.y + (this.startSize.height - newSize.height)
                break
            case 'w':
                newX = this.startCellPos.x + (this.startSize.width - newSize.width)
                break
            case 'sw':
                newX = this.startCellPos.x + (this.startSize.width - newSize.width)
                break
            default:
                return null // 不需要调整位置
        }

        return { x: newX, y: newY }
    }

    /**
     * 鼠标释放处理
     */
    onMouseUp() {
        if (!this.isResizing) return

        this.stopResize()
    }

    /**
     * 停止拖拽
     */
    stopResize() {
        this.isResizing = false

        // 移除拖拽样式
        if (this.currentHandle) {
            const className = this.currentHandle.getAttribute('class')
            this.currentHandle.setAttribute('class', className.replace(' dragging', ''))
            this.currentHandle = null
        }

        // 移除全局事件
        document.removeEventListener('mousemove', this.onMouseMove)
        document.removeEventListener('mouseup', this.onMouseUp)

        // 恢复文本选择
        document.body.style.userSelect = ''


        //持久化
            window._windowGraph?.saveCanvasToStorage?.();
    }

    /**
     * 更新SVG容器和拖拽点位置（节点尺寸变化时调用）
     */
    updateSVGHandles() {
        if (!this.svgContainer) return

        const cellSize = this.cell.getSize()

        // 更新SVG容器尺寸
        this.svgContainer.style.width = `${cellSize.width + 20}px`
        this.svgContainer.style.height = `${cellSize.height + 20}px`

        // 更新拖拽点位置
        const positions = [
            //   { cx: 10, cy: 10 }, // nw
            //   { cx: cellSize.width / 2 + 10, cy: 10 }, // n
            //   { cx: cellSize.width + 10, cy: 10 }, // ne
            //   { cx: 10, cy: cellSize.height / 2 + 10 }, // w
            //   { cx: cellSize.width + 10, cy: cellSize.height / 2 + 10 }, // e
            //   { cx: 10, cy: cellSize.height + 10 }, // sw
            //   { cx: cellSize.width / 2 + 10, cy: cellSize.height + 10 }, // s
            { cx: cellSize.width - 10, cy: cellSize.height - 10 } // se
        ]

        this.resizeHandles.forEach((handle, index) => {
            handle.setAttribute('cx', positions[index].cx)
            handle.setAttribute('cy', positions[index].cy)
        })
    }

    /**
     * 显示SVG拖拽点
     */
    showHandles() {
        if (!this.isVisible && this.svgContainer) {
            this.svgContainer.style.display = 'block'
            this.isVisible = true
            // 确保拖拽点位置是最新的
            this.updateSVGHandles()
        }
    }

    /**
     * 隐藏SVG拖拽点
     */
    hideHandles() {
        if (this.isVisible && !this.isResizing && this.svgContainer) {
            this.svgContainer.style.display = 'none'
            this.isVisible = false
        }
    }

    /**
     * 销毁控制器
     */
    destroy() {
        // 移除事件监听
        document.removeEventListener('mousemove', this.onMouseMove)
        document.removeEventListener('mouseup', this.onMouseUp)

        // 移除DOM元素
        if (this.svgContainer && this.svgContainer.parentNode) {
            this.svgContainer.parentNode.removeChild(this.svgContainer)
        }

        // 清理引用
        this.resizeHandles = []
        this.svgContainer = null
        this.currentHandle = null
    }
}